import './index.scss';

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { MeshLine, MeshLineMaterial, MeshLineRaycast } from './plugin';
import TWEEN from '@tweenjs/tween.js';

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 3, 5);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

window.addEventListener('resize', () => {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
});

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;

const group = new THREE.Group();
group.rotation.x = -Math.PI / 2;
scene.add(group);

const points = [];
for (let i = 0; i <= 10; i++) {
  points.push(new THREE.Vector3(i - 5, Math.random(), 0));
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new MeshLine();
line.setGeometry(geometry);

const loader = new THREE.TextureLoader();
const texture = loader.load('./spriteline.png');
texture.colorSpace = THREE.SRGBColorSpace;
texture.repeat.set(1, 1);
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;

const material = new MeshLineMaterial({
  color: 0x00ffff,
  lineWidth: 0.1,
  map: texture,
  transparent: true,
});

const mesh = new THREE.Mesh(line, material);
group.add(mesh);

new TWEEN.Tween({ x: 0, y: 0 })
  .to({ x: -1, y: 0 })
  .dynamic(true)
  .duration(3000)
  .repeat(Infinity)
  .onUpdate(({ x, y }) => {
    if (material.map) {
      material.map.offset.x = x;
      material.map.offset.y = y;
    }
  })
  .start();

const clock = new THREE.Clock();
let delta;

function animate() {
  requestAnimationFrame(animate);

  delta = clock.getDelta();

  controls.update();

  renderer.render(scene, camera);

  TWEEN.update();
}

animate();
